<?php

namespace App\Http\Controllers\V1;

use Exception;
use App\Support\Code;
use App\Models\Address;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AddressController extends ApiController
{
    public function store(Request $request)
    {
        $user = $this->getUser();
        $user->addresses()->create([
            'type' => $request->type,
            'address' => $request->address,
            'currency' => $request->currency,
            'remark' => $request->post('remark', '')
        ]);

        return $this->success();
    }

    public function index(Request $request)
    {
        $user = $this->getUser();
        $addresses = Address::where('user_id', $user->id)
            ->where('currency', $request->currency)
            ->where('type', $request->type)->get()->toArray();
        return $this->success($addresses);
    }

    public function destroy($id)
    {
        $user = $this->getUser();
        $address = Address::find($id);
        if ($address->user_id != $user->id) {
            return $this->fail(Code::PARAMETER_ERROR, '非法请求！');
        }
        try {
            $address->delete();
        } catch (Exception $exception) {
            Log::error($exception->getMessage());
        }
        return $this->setMsg('删除成功')->success();
    }
}
